from sqlalchemy.orm import Session
from app.models.models import Student, Interest, Preference, Building, Room
from app.schemas import Gender, SleepingHabit, Cleanliness
from app.auth import get_password_hash
import random

def generate_unique_student_data(count=100):
    """生成唯一的学生数据"""
    majors = [
        "计算机科学", "软件工程", "人工智能", "数据科学", "网络工程",
        "信息安全", "物联网工程", "电子信息工程", "通信工程", "自动化"
    ]
    
    first_names = {
        Gender.MALE: ["伟", "强", "磊", "勇", "军", "杰", "涛", "超", "明", "浩",
                     "鹏", "飞", "宇", "斌", "辉", "峰", "波", "龙", "健", "帅"],
        Gender.FEMALE: ["芳", "娟", "敏", "静", "秀", "丽", "艳", "娜", "燕", "玲",
                       "华", "红", "梅", "雪", "莉", "倩", "琳", "婷", "萍", "英"]
    }
    
    last_names = ["张", "李", "王", "赵", "刘", "陈", "杨", "黄", "周", "吴",
                  "郑", "孙", "马", "朱", "胡", "郭", "何", "高", "林", "罗"]
    
    # 生成所有可能的学号
    all_ids = []
    for gender_code in ['1', '2']:  # 1为男生，2为女生
        for i in range(1, count//2 + 1):
            student_id = f"2023{gender_code}{i:03d}"
            all_ids.append((student_id, Gender.MALE if gender_code == '1' else Gender.FEMALE))
    
    students_data = []
    used_emails = set()
    
    for student_id, gender in all_ids:
        # 生成唯一的姓名和邮箱
        while True:
            name = random.choice(last_names) + random.choice(first_names[gender])
            email = f"student_{student_id}@example.com"
            if email not in used_emails:
                used_emails.add(email)
                break
        
        student = {
            "student_id": student_id,
            "name": name,
            "email": email,
            "password": "123456",
            "gender": gender,
            "major": random.choice(majors),
            "grade": random.randint(1, 4),
            "sleeping_habit": random.choice(list(SleepingHabit)),
            "cleanliness": random.choice(list(Cleanliness))
        }
        students_data.append(student)
    
    return students_data

def init_test_data(db: Session):
    """初始化测试数据"""
    try:
        print("开始初始化测试数据...")
        
        # 生成100个学生数据（男女各半）
        students_data = generate_unique_student_data(100)
        
        print(f"开始创建{len(students_data)}个学生数据...")
        for student_data in students_data:
            student = Student(
                student_id=student_data["student_id"],
                name=student_data["name"],
                email=student_data["email"],
                hashed_password=get_password_hash(student_data["password"]),
                gender=student_data["gender"],
                major=student_data["major"],
                grade=student_data["grade"],
                sleeping_habit=student_data["sleeping_habit"],
                cleanliness=student_data["cleanliness"],
                is_active=True
            )
            db.add(student)
        
        try:
            db.commit()
            print("学生数据创建成功")
        except Exception as e:
            db.rollback()
            print(f"创建学生数据失败: {str(e)}")
            return
        
        # 创建兴趣标签
        interest_tags = [
            "运动", "音乐", "游戏", "阅读", "电影", "旅行", "摄影", "美食",
            "编程", "绘画", "动漫", "篮球", "足球", "游泳", "健身", "烹饪"
        ]
        
        print("创建偏好设置...")
        students = db.query(Student).all()
        for student in students:
            # 为每个学生选择4个兴趣标签
            selected_tags = random.sample(interest_tags, 4)
            
            preference = Preference(
                student_id=student.id,
                interest_tags=selected_tags
            )
            db.add(preference)
        
        try:
            db.commit()
            print("偏好设置创建成功")
        except Exception as e:
            db.rollback()
            print(f"创建偏好设置失败: {str(e)}")
            return
        
        # 创建宿舍楼
        print("创建宿舍楼数据...")
        buildings_data = [
            {
                "name": "男生1号楼",
                "floors": 6,
                "rooms_per_floor": 10,
                "gender": Gender.MALE
            },
            {
                "name": "女生1号楼",
                "floors": 6,
                "rooms_per_floor": 10,
                "gender": Gender.FEMALE
            }
        ]
        
        for building_data in buildings_data:
            building = Building(**building_data)
            db.add(building)
            try:
                db.commit()
                print(f"创建宿舍楼成功: {building_data['name']}")
                
                # 为每个宿舍楼创建房间
                print(f"为{building_data['name']}创建房间...")
                for floor in range(1, building_data['floors'] + 1):
                    for room_num in range(1, building_data['rooms_per_floor'] + 1):
                        room_number = f"{building_data['name']}-{floor}0{room_num}"
                        room = Room(
                            building_id=building.id,
                            floor=floor,
                            room_number=room_number,
                            capacity=4,
                            current_occupancy=0
                        )
                        db.add(room)
                
                db.commit()
                print(f"{building_data['name']}的房间创建成功")
                
            except Exception as e:
                db.rollback()
                print(f"创建宿舍楼或房间失败: {str(e)}")
                return
        
        print("测试数据初始化完成")
        
    except Exception as e:
        print(f"初始化过程中发生错误: {str(e)}")
        db.rollback() 